/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package wang.lcs.pay.util.print;

import java.util.concurrent.atomic.AtomicReference;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 *
 * @author Rossen Stoyanchev
 * @author Rob Winch
 * @since 3.2
 */
public class HttpResult {

    private static final Object RESULT_NONE = new Object();

    private final HttpServletRequest mockRequest;

    private final HttpServletResponse mockResponse;

    private final AtomicReference<Object> asyncResult = new AtomicReference<Object>(RESULT_NONE);

    /**
     * Create a new instance with the given request and response.
     */
    public HttpResult(HttpServletRequest request, HttpServletResponse response) {
        this.mockRequest = request;
        this.mockResponse = response;
    }

    public HttpServletRequest getRequest() {
        return this.mockRequest;
    }

    public HttpServletResponse getResponse() {
        return this.mockResponse;
    }

    public FlashMap getFlashMap() {
        return RequestContextUtils.getOutputFlashMap(this.mockRequest);
    }

    public void setAsyncResult(Object asyncResult) {
        this.asyncResult.set(asyncResult);
    }

    public Object getAsyncResult() {
        return getAsyncResult(-1);
    }

    public Object getAsyncResult(long timeToWait) {
        if (this.mockRequest.getAsyncContext() != null) {
            timeToWait = (timeToWait == -1 ? this.mockRequest.getAsyncContext().getTimeout() : timeToWait);
        }
        Object result = this.asyncResult.get();
        Assert.state(result != RESULT_NONE, "Async result was not set");
        return this.asyncResult.get();
    }

}
